$(document).ready(function () {

    $("#storeSelect").selectpicker();
    $("#employeeSelect").selectpicker();
    $("#accountMoneySelect").selectpicker();
    $("#supplierSelect").selectpicker();
    $('#inputOrderTable').DataTable({
        destroy: true,
        searching: false,
        paging: true,//表格分页
        lengthChange: false
    });
    $('#productTable').DataTable({
        destroy: true,
        searching: false,
        paging: true,//表格分页
        lengthChange: false
    });
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "7000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    setInputOrderNumber($("#inputOrderNumber"))
    setInputOrderDate($("#inpDate"))
    listEmployees($("#employeeSelect"))
    listStores($("#storeSelect"))
    listMoneyAccount($("#accountMoneySelect"))
    listSupplier($("#supplierSelect"))
    //失去焦点事件
    // $('#inputNumber' + product.id).blur(function (){
    //     //数量和进价相乘,设置到金额一列
    //
    //
    // })

});

function listSupplier(obj){
    $.ajax({
        type: 'get',
        url: "/admin/info/supplier/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].supName + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

function printInputOrder(){
    let newstr = document.getElementById("print").innerHTML;
    let oldstr = document.body.innerHTML;
    document.body.innerHTML = newstr;
    window.print();
    document.body.innerHTML = oldstr;
}
function saveAndPrintInputOrder(){
    let inputOrder={}
    inputOrder.orderId = $('#checkInputOrderNumber').text()
    inputOrder.supplier= $('#checkSupplier').text()
    inputOrder.employeeId = $('#employeeSelect').val()
    inputOrder.accountMoeny = $('#accountMoneySelect').val()
    inputOrder.storeId = $('#storeSelect').val()
    inputOrder.inputDate = $("#inpDate").val()
    inputOrder.price = $('#sumMoney').text()
    inputOrder.back = $('#backup').val()
    inputOrder.products = localStorage.getItem("products");
    //商品信息
    console.log(inputOrder.products)
    console.log(inputOrder)
    localStorage.removeItem('productIds')
    $.ajax({
        type: 'post',
        url: "/admin/business/inputOrder/save",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(inputOrder),
        success: function (resp) {
            console.log(resp)
            if (resp.data){
                toastr.success(resp.message+',正在跳转...','提示')
                setTimeout(function () {
                    window.location.href='/admin/business/inputOrder/print/'+resp.data
                },2000)
            }else{
                toastr.error(resp.message,'提示')
            }
        }
    });
}
/**
 * 保存进货单据
 */
function saveInputOrder(){
    let inputOrder={}
    inputOrder.orderId = $('#checkInputOrderNumber').text()
    inputOrder.supplier= $('#supplierSelect').val()
    inputOrder.employeeId = $('#employeeSelect').val()
    inputOrder.accountMoeny = $('#accountMoneySelect').val()
    inputOrder.storeId = $('#storeSelect').val()
    inputOrder.inputDate = $("#inpDate").val()
    inputOrder.price = $('#sumMoney').text()
    inputOrder.back = $('#backup').val()
    inputOrder.products = localStorage.getItem("products");
    //商品信息
    console.log(inputOrder.products)
    console.log(inputOrder)
    localStorage.removeItem('productIds')
    $.ajax({
        type: 'post',
        url: "/admin/business/inputOrder/save",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(inputOrder),
        success: function (resp) {
            console.log(resp)
            if (resp.data){
                toastr.success(resp.message,'提示')
                setTimeout(function () {
                    window.location.reload()
                },2000)
            }else{
                toastr.error(resp.message,'提示')
            }
        }
    });
}

/**
 * 单据保存显示页面
 */
function showInputOrderInfo() {
    //单据编号
    $('#checkInputOrderNumber').text($('#inputOrderNumber').val())
    //经手人
    $('#checkEmployee').text($('#employeeSelect').find("option:selected").text())
    //仓库
    $('#checkStore').text($('#storeSelect').find("option:selected").text())
    //付款账户
    $('#checkAccountMoney').text($('#accountMoneySelect').find("option:selected").text())
    $('#checkInputOrderDate').text($("#inpDate").val())
    $('#checkSupplier').text($('#supplierSelect').find("option:selected").text())
    let data = localStorage.getItem('data')
    data = JSON.parse(data)
    if (data!==null){
        $("#inputOrderCheckTable").DataTable({
            destroy: true,
            //数据源
            data: data,
            //取消搜索栏
            bFilter: false,
            bLengthChange: false,
            //给每列赋值
            columns: [
                {
                    data: 'bproId', render: function (data, type, row, meta) {
                        return row.bproId === null || row.bproId === undefined ? "" : row.bproId;
                    }
                },
                {
                    data: 'bproTitle', render: function (data, type, row) {
                        return row.bproTitle === null || row.bproTitle === undefined ? "" : row.bproTitle;
                    }
                },
                {
                    data: 'bproUnit', render: function (data, type, row) {
                        return row.bproUnit === null || row.bproUnit === undefined ? "" : row.bproUnit;
                    }
                },


                {
                    data: 'binputPrice', render: function (data, type, row, meta) {
                        return row.binputPrice === null || row.binputPrice === undefined ? "" : row.binputPrice;
                    }
                },
                {
                    data: 'bproNum', render: function (data, type, row) {
                        return row.bproNum === null || row.bproNum === undefined ? "" : row.bproNum;
                    }
                },
                {
                    data: 'eachSum', render: function (data, type, row) {
                        return row.eachSum === null || row.eachSum === undefined ? "" : row.eachSum;
                    }
                },
            ],
            footerCallback: function (row, data, start, end, display) {
                var api = this.api(), data;
                var intVal = function (i) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '') * 1 :
                        typeof i === 'number' ? i : 0;

                };
                //当前页统计
                // total = api.column(5).data().reduce(function (a, b) { return intVal(a) + intVal(b); }, 0);
                //总价
                pageTotal = api.column(5, {page: 'current'}).data().reduce(function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0);
                let selects=[]
                api.column(0, {page: 'current'}).data().each(function (a){
                    selects.push(a)
                })
                localStorage.setItem('productIds',selects)
                console.log(selects)
                $('#sumMoney').text(pageTotal)
            },
        })
    }

}

/**
 * 列出所有的支付账户信息
 */
function listMoneyAccount(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/moneyAccount/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].accId + '" >' + data[i].accName + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 金额计算
 */
function payMoney() {
    let money = localStorage.getItem('payMoney')
    $('#payMoney').val(money)
    localStorage.removeItem('payMoney')
}

/**
 * 列出所有的库存地址
 * @param obj
 */
function listStores(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/store/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].bstoId + '" >' + data[i].bstoTitle + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 列出所有的职工
 * @param obj
 */
function listEmployees(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/employee/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].name + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 默认进货日期
 * @param obj
 */
function setInputOrderDate(obj) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    obj.val(year + '-' + month + '-' + day)
}

/**
 * 设置单据编号
 */
function setInputOrderNumber(obj) {
    //日期格式化为指定格式
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }

        return fmt;
    }
    obj.val(new Date().format("yyyyMMddhhmmss"))
}

/**
 * 获得所有商品到列表中
 */
function getAllProducts() {
    $.get("/admin/business/inputOrder/product/listAll", {}, function (resp) {
        //保存到localStore中

        //渲染datatabls表格
        $("#productTable").DataTable({
            destroy: true,
            //数据源
            data: resp,
            //取消搜索栏
            bFilter: false,
            bLengthChange: false,
            //给每列赋值
            columns: [
                {
                    data: 'bproId', render: function (data, type, row, meta) {
                        return '<input name="inp-product-box" class="inp-product-box" type="checkbox" value="' + row.bproId + '">'
                    }
                },
                {
                    data: 'bproId', render: function (data, type, row, meta) {
                        return row.bproId;
                    }
                },
                {
                    data: 'bproTitle', render: function (data, type, row) {
                        return row.bproTitle === null || row.bproTitle === undefined ? "" : row.bproTitle;
                    }
                },
                {
                    data: 'bproUnit', render: function (data, type, row) {
                        return row.bproUnit === null || row.bproUnit === undefined ? "" : row.bproUnit;
                    }
                },


                {
                    data: 'binputPrice', render: function (data, type, row, meta) {
                        return ' <input type="text" class="form-control" id="inputPrice' + row.bproId + '" value="'+row.binputPrice+'" placeholder="请输入进价">';
                    }
                },
                {
                    data: 'bproNum', render: function (data, type, row) {
                        return ' <input type="text" class="form-control" id="inputNumber' + row.bproId + '" placeholder="请输入进货数量">';
                    }
                },
            ],


        })
    })
}

/**
 * 添加商品到进货单
 */
function save2InputOrderList() {

    let selects = [];
    let count = 0;
    // $("#productTable").dataTable().fnGetNodes()[1].firstElementChild.firstElementChild.outerHTML
    // var tbl = $("#productTable").dataTable();
    // var trList = tbl.fnGetNodes();
    // for(i=0;i<trList.length;i++){
    //     var trObj = trList[i];
    //     //接下来就和 案1 的一样了 就只写个输出 不做实现了
    //     console.log(trObj.firstElementChild.firstElementChild.checked);
    // }
    // $("#productTable").dataTable().fnGetNodes()[1].innerHTML.getElementsByClassName
    console.log(selects)
    $("input[name='inp-product-box']:checked").each(function () {
        const product = {};
        if ($(this).prop('checked')) {
            //如果当前属性为checked
            product.bproId = $(this).val()
            product.binputPrice=$('#inputPrice' + product.bproId).val()
            if (product.binputPrice.length === 0){
                toastr.error('请输入进价','提示')
                $('#inputPrice' + product.bproId).focus()
                return 0;
            }
            product.bproNum = $('#inputNumber' + product.bproId).val()
            product.eachSum = product.binputPrice*product.bproNum
            selects.push(product)
        }
    });
    if (selects.length === 0) {
        swal("您没有选中任何数据，请选中后重试！");
    }
    //保存到localstore中
    localStorage.setItem("products",JSON.stringify(selects))
    $.ajax({
        type: 'post',
        url: "/admin/business/inputOrder/show2Table",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(selects),
        success: function (resp) {
            $("#myModal").modal('hide')
            let jsonData = JSON.stringify(resp)
            localStorage.setItem('data', jsonData)
            $("#inputOrderTable").DataTable({
                destroy: true,
                //数据源
                data: resp,
                //取消搜索栏
                bFilter: false,
                bLengthChange: false,
                //给每列赋值
                columns: [
                    {
                        data: 'bproId', render: function (data, type, row, meta) {
                            return row.bproId;
                        }
                    },
                    {
                        data: 'bproTitle', render: function (data, type, row) {
                            return row.bproTitle === null || row.bproTitle === undefined ? "" : row.bproTitle;
                        }
                    },
                    {
                        data: 'bproUnit', render: function (data, type, row) {
                            return row.bproUnit === null || row.bproUnit === undefined ? "" : row.bproUnit;
                        }
                    },


                            {
                                data: 'binputPrice', render: function (data, type, row, meta) {
                                    return row.binputPrice === null || row.binputPrice === undefined ? "暂无" : row.binputPrice;
                                }
                            },
                            {
                                data: 'bproNum', render: function (data, type, row) {
                                    return row.bproNum === null || row.bproNum === undefined ? "暂无" : row.bproNum;
                                }
                            },
                            {
                                data: 'eachSum', render: function (data, type, row) {
                                    return row.eachSum === null || row.eachSum === undefined ? "暂无" : row.eachSum;
                                }
                            },
                        ],
                        footerCallback: function (row, data, start, end, display) {
                            var api = this.api(), data;
                            var intVal = function (i) {
                                return typeof i === 'string' ?
                                    i.replace(/[\$,]/g, '') * 1 :
                                    typeof i === 'number' ? i : 0;

                            };
                            //当前页统计
                            // total = api.column(5).data().reduce(function (a, b) { return intVal(a) + intVal(b); }, 0);
                            //全部统计
                            pageTotal = api.column(5, {page: 'current'}).data().reduce(function (a, b) {
                                return intVal(a) + intVal(b);
                            }, 0);
                            localStorage.setItem('payMoney', pageTotal)
                        },

            })
            payMoney()
        }
    });
}

